from machine import FPIOA,PWM
from machine import Pin
#import time, os, sys
class MOTOR:
    def __init__(self, ain1_pin, ain2_pin, pwm_pin, freq, duty):
        #静态参数
#        self.ain1_pin = ain1_pin
#        self.ain2_pin = ain2_pin
        self.pwm_pin = pwm_pin
        self.freq = freq
        self.duty = duty

        self.fpioa = FPIOA()
        self.fpioa.set_function(ain1_pin,FPIOA.GPIO48)
        self.fpioa.set_function(ain2_pin,FPIOA.GPIO49)
        self.AIN1= Pin(ain1_pin, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
        self.AIN2= Pin(ain2_pin, Pin.OUT, pull=Pin.PULL_NONE, drive=7)
        # 配置排针引脚号32，芯片引脚号为46的排针复用为PWM通道2输出
        pwm_io = FPIOA()
        pwm_io.set_function(pwm_pin, FPIOA.PWM2)
        # 配置PWM2,频率,占空比%
        self.pwm_motor = PWM(2, self.freq, self.duty, enable=True)
        #self.pwm_motor.duty(0)    默认占空比0%

        #正转
    def fo(self, speed):
        self.AIN1.high()
        self.AIN2.low()
        self.pwm_motor.duty(speed)

        #反转
    def bo(self, speed):
        self.AIN2.high()
        self.AIN1.low()
        self.pwm_motor.duty(speed)

        #反转
    def stop(self):
       self.AIN2.low()
       self.AIN1.low()
       self.pwm_motor.duty(0)

        #根据正负值设置电机正反转
    def set_motor(self, speed):
        if speed > 0:
            self.fo(speed)
        elif speed < 0:
            speed = -speed
            self.bo(speed)
        else:
            self.stop()

#motor = MOTOR(48, 49, 46, 10000, 0)

#try:

#    i = 0
#    while True:
#        i = i - 1
#        motor.set_motor(i)
#        if i < -50:
#            i=0
#            time.sleep(3)
#        time.sleep(0.05)  # 等待0.01秒
#except KeyboardInterrupt:
#    print("Program stopped by user")
#except Exception as e:
#    print(f"Error occurred: {str(e)}")
#finally:
#    # 清理资源
#    os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
#    time.sleep_ms(100)
#    print("System shutdown complete")
